<template>
  <div class="login">
    <el-form v-show="isForm && !passwordReset" ref="loginForm" :model="loginForm" :rules="loginRules"
      class="login-form">
      <h2 class="title">进修管理平台</h2>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码"
          @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%"
          @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img" />
        </div>
      </el-form-item>
      <div style="display: flex;justify-content: space-between;">
        <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
        <span @click="passwordReset = true" style="cursor: pointer;font-size: 14px;">忘记密码?</span>
      </div>
      <el-form-item style="width: 100%">
        <el-button :loading="loading" size="medium" type="primary" style="width: 100%"
          @click.native.prevent="handleLoginBefore">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>

    <div id="captcha-box" v-show="!passwordReset"></div>

    <!--  底部  -->
    <div class="el-login-footer">
      <span></span>
    </div>
    <el-card class="box-card" v-show="passwordReset">
      <div slot="header" class="clearfix">
        <span>华山医院教育一网通办</span>
      </div>
      <el-form :model="form" label-position="left" label-width="80px" :rules="rules" ref="passwordResetForm"
        class="demo-ruleForm">
        <!-- 手机号 -->
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <!-- 身份证号 -->
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证号"></el-input>
        </el-form-item>


        <!-- 新密码 -->
        <el-form-item label="新密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入新密码"></el-input>
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="form.confirmPassword" type="password" placeholder="请再次输入新密码"></el-input>
        </el-form-item>
      </el-form>
      <div style="display: flex;justify-content: space-around;">
        <el-button @click="passwordReset = false">返回登录</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getCodeImg, resetPassword } from "@/api/login";
import { decrypt, encrypt } from "@/utils/jsencrypt";
import Cookies from "js-cookie";

export default {
  name: "Login",

  data() {
    // 自定义验证规则：确认密码必须与新密码一致
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error("两次密码不一致"));
      } else {
        callback();
      }
    };
    return {
      passwordReset: false,

      baseUrl: process.env.VUE_APP_BASE_API,
      codeUrl: "",
      rules: {
        // 手机号验证规则
        phonenumber: [
          { required: true, message: "手机号输入不能为空", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        // 身份证号验证规则
        idCard: [
          { required: true, message: "身份证号码输入不能为空", trigger: "blur" },
          {
            pattern: /^\d{17}[\dXx]$/,
            message: "身份证号码错误，请重新输入",
            trigger: "blur",
          },
        ],
        // 姓名验证规则
        // userName: [
        //   { required: true, message: "姓名输入不能为空", trigger: "blur" },
        //   {
        //     pattern: /^[\u4e00-\u9fa5]{2,4}$/,
        //     message: "请输入2-4个汉字",
        //     trigger: "blur",
        //   },
        // ],
        // 新密码验证规则
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
        // 确认密码验证规则
        confirmPassword: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { validator: validateConfirmPassword, trigger: "blur" },
        ],
      },
      form: {
        phonenumber: "", // 手机号
        idCard: "", // 身份证号
        // userName: "", // 姓名
        password: "", // 新密码
        confirmPassword: "", // 确认密码
      },
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
      },
      loading: false,
      // 验证码开关
      captchaEnabled: false,
      // 注册开关
      register: false,
      redirect: undefined,
      // 行为验证码
      isForm: true,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  methods: {
    // 提交重置密码表单
    submitForm() {
      this.$refs.passwordResetForm.validate((valid) => {
        if (valid) {
          // 表单验证通过，提交数据
          resetPassword(this.form).then(() => {
            this.$message.success("密码重置成功");
            this.passwordReset = false;
            // 清空表单数据
            this.$refs.passwordResetForm.resetFields();
          }).catch(() => {
            this.$message.error("密码重置失败，请重试");
          });
        } else {
          // 表单验证失败
          this.$message.error("请检查输入内容");
          return false;
        }
      });
    },
    // 重置表单
    resetForm() {
      this.$refs.passwordResetForm.resetFields();
    },
    getCode() {
      getCodeImg().then((res) => {
        this.captchaEnabled =
          res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    handleLoginBefore() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.isForm = false;
          this.initCaptcha();
        }
      });
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), {
              expires: 30,
            });
            Cookies.set("rememberMe", this.loginForm.rememberMe, {
              expires: 30,
            });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }
          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || "/" }).catch(() => { });
            })
            .catch(() => {
              this.loading = false;
              if (this.captchaEnabled) {
                this.getCode();
              }
            });
        }
      });
    },
    initCaptcha() {
      // config 对象为TAC验证码的一些配置和验证的回调
      const config = {
        // 生成接口 (必选项,必须配置, 要符合tianai-captcha默认验证码生成接口规范)
        requestCaptchaDataUrl: this.baseUrl + "/tianaiCaptcha/generate",
        // 验证接口 (必选项,必须配置, 要符合tianai-captcha默认验证码校验接口规范)
        validCaptchaUrl: this.baseUrl + "/tianaiCaptcha/check",
        // 验证码绑定的div块 (必选项,必须配置)
        bindEl: "#captcha-box",
        // 验证成功回调函数(必选项,必须配置)
        validSuccess: (res, c, tac) => {
          // 销毁验证码服务
          tac.destroyWindow();
          this.isForm = true;
          this.handleLogin();
        },
        // 验证失败的回调函数(可忽略，如果不自定义 validFail 方法时，会使用默认的)
        validFail: (res, c, tac) => {
          tac.reloadCaptcha();
        },
        // 刷新按钮回调事件
        btnRefreshFun: (el, tac) => {
          tac.reloadCaptcha();
        },
        // 关闭按钮回调事件
        btnCloseFun: (el, tac) => {
          tac.destroyWindow();
          this.isForm = true;
        },
      };
      // 一些样式配置， 可不传
      let style = {
        logoUrl: null, // 去除logo
        // logoUrl: "/xx/xx/xxx.png" // 替换成自定义的logo
      };
      // 参数1 为 tac文件是目录地址， 目录里包含 tac的js和css等文件
      // 参数2 为 tac验证码相关配置
      // 参数3 为 tac窗口一些样式配置
      let url =
        process.env.NODE_ENV === "production"
          ? "/engage-web/static/tac"
          : "/static/tac";
      window
        .initTAC(url, config, style)
        .then((tac) => {
          tac.init(); // 调用init则显示验证码
        })
        .catch((e) => {
          console.log("初始化tac失败", e);
        });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-bg.jpg");
  background-size: cover;
}

.box-card {
  width: 400px;
}

.link-type {
  color: #a2292b;
}

.clearfix {
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
  font-weight: bolder;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: "Microsoft YaHei";
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}
</style>
